package com.jtny;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Knife4j配置类
 *
 * @author 智慧能源中心-夏燕强
 * @version 2.0
 * @package com.jtny
 * @fileName Knife4jConfig.java
 * @createTime 2023年09月13日 15:41
 * @Copyright© 2023 jtny
 * 江投能源技术研究院 版权所有
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Knife4jConfig {

    @Bean
    public Docket createAllRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .groupName("01.全部")
                .apiInfo(allApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.jtny.nytb"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo allApiInfo() {
        return new ApiInfoBuilder()
                .description("江投能源碳宝设备管理Restful接口")
                .contact(new Contact("夏燕强", "", ""))
                .version("1.0.0-SNAPSHOT")
                .title("江投能源碳宝设备管理Restful接口")
                .build();

    }

    @Bean
    public Docket createPageConfigRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .groupName("02.设备管理服务")
                .apiInfo(pageConfigApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.jtny.nytb.energymonitor.equipment"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo pageConfigApiInfo() {
        return new ApiInfoBuilder()
                .description("江投能源碳宝能碳监测管理 - 设备管理服务Restful接口")
                .contact(new Contact("夏燕强", "", ""))
                .version("1.0.0-SNAPSHOT")
                .title("江投能源碳宝能碳监测管理 - 设备管理服务Restful接口")
                .build();

    }

    @Bean
    public BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    if (field == null) {
                        return new ArrayList<>();
                    }

                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }
}
